package com.hgyc.mom.system.controller;

import java.util.*;

import com.hgyc.mom.common.context.FileServiceContext;
import com.hgyc.mom.common.exception.file.FileException;
import com.hgyc.mom.common.util.file.FileUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.beans.BeanUtils;
import org.springframework.web.multipart.MultipartFile;
import com.hgyc.mom.system.entity.SysAttachment;
import com.hgyc.mom.system.vo.SysAttachmentParam;
import com.hgyc.mom.system.service.SysAttachmentService;
import com.hgyc.mom.common.vo.Result;

import com.hgyc.mom.core.mybatis.QueryWrapperUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

/**
 * 附件Controller
 *
 * @author fwj
 * @since 2025-04-27
 */
@Slf4j
@Tag(name = "附件控制器", description = "附件控制器")
@RestController
@RequestMapping("/system/attachment")
public class SysAttachmentController
{
    @Autowired
    private SysAttachmentService sysAttachmentService;

    @Autowired
    private FileServiceContext fileServiceContext;

    @Operation(summary = "查询附件列表", description = "查询附件列表")
    @PostMapping("/pageList")
    public Result<IPage<SysAttachment>> pageList(@Parameter(description = "查询参数") @RequestBody SysAttachmentParam sysAttachmentParam)
    {
        Page<SysAttachment> page = new Page<>(sysAttachmentParam.getPage(), sysAttachmentParam.getPageSize());
        SysAttachment sysAttachment = new SysAttachment();
        BeanUtils.copyProperties(sysAttachmentParam, sysAttachment);
        QueryWrapper<SysAttachment> wrapper = QueryWrapperUtil.build(sysAttachment);
        IPage<SysAttachment> list = sysAttachmentService.page(page, wrapper);
        return Result.success(list);
    }


    /**
     * 通用上传请求（单个）
     */
    @PostMapping("/upload")
    public Result<SysAttachment> uploadFile(@RequestParam("file") MultipartFile file) throws Exception
    {
        try
        {
            // 上传并返回新文件名称
            String filePath = fileServiceContext.uploadFile(file);

            SysAttachment sysAttachment = new SysAttachment();
            sysAttachment.setFileName(file.getOriginalFilename());
            sysAttachment.setFileUrl(filePath);
            sysAttachment.setFileType(FileUtils.getExtension(file));
            sysAttachment.setFileSize(file.getSize());
            sysAttachmentService.save(sysAttachment);

            return Result.success("上传成功！",sysAttachment);
        }
        catch (Exception e)
        {
            return Result.error(e.getMessage());
        }
    }

    /**
     * 下载文件
     *
     * @param attachmentId 附件ID
     */
    @GetMapping("/download/{attachmentId}")
    public void fileDownload(@PathVariable("attachmentId") Long attachmentId, HttpServletResponse response, HttpServletRequest request)
    {
        try
        {
            SysAttachment sysAttachment = sysAttachmentService.getById(attachmentId);
            if (sysAttachment == null) {
                throw new FileException("获取文件失败！");
            }

            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            FileUtils.setAttachmentResponseHeader(response, sysAttachment.getFileName());

            byte[] bytes = fileServiceContext.downloadFile(sysAttachment.getFileUrl());

            FileUtils.writeBytes(bytes, response.getOutputStream());

        }catch (Exception e){
            log.error("下载文件失败", e);
            throw new FileException("下载文件失败！", e);
        }
    }


    @Operation(summary = "删除附件", description = "删除附件")
    @DeleteMapping
    public Result remove(@Parameter(description = "删除ID") @RequestParam("ids") Long[] ids)
    {
        sysAttachmentService.removeFiles(Arrays.asList(ids));
        return Result.success();
    }

}
